/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.vcs;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.ISVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import com.mobaas.devops.VcsProvider;
import com.mobaas.devops.model.VcsDayStat;
import com.mobaas.devops.model.VcsMonthStat;

/**
 * Svn访问实现
 * @author billy zhang
 *
 */
public class SvnProviderImpl implements VcsProvider {

	private String repoUrl;
	private String username;
	private String password;

	public void init(Map<String, Object> config) {
		this.repoUrl = (String)config.get("repoUrl");
		this.username = (String)config.get("username");
		this.password = (String)config.get("password");
	}

	public List<VcsDayStat> getLastDayStatList() {
		
		DAVRepositoryFactory.setup();
		
        //定义svn版本库的URL。
        SVNURL repositoryURL = null;
        //定义版本库。
        SVNRepository repository = null;
        /*
         * 实例化版本库类
         * */
        try {
        	//获取SVN的URL。
        	repositoryURL=SVNURL.parseURIEncoded(repoUrl);
        	//根据URL实例化SVN版本库。

        	ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        	 
    		// 实例化客户端管理类
        	SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, username, password);

        	repository = clientManager.createRepository(repositoryURL, false);

        } catch (SVNException svne) {
            svne.printStackTrace();
        }
    	
        try {
	        // 过滤条件  
        	Calendar cal1 = Calendar.getInstance();
        	cal1.set(Calendar.HOUR_OF_DAY, 0);
        	cal1.set(Calendar.MINUTE, 0);
        	cal1.set(Calendar.SECOND, 0);
        	cal1.set(Calendar.MILLISECOND, 0);
        	final Date begin = cal1.getTime();
        	
        	cal1.add(Calendar.DAY_OF_MONTH, 1);
        	final Date end = cal1.getTime();
        	
	        final String author = "";  
	        long startRevision = 0;  
	        long endRevision = -1;//表示最后一个版本  
	        final Map<String, List<String>> totalByAnthor = new HashMap<>();  
	        
	        //String[] 为过滤的文件路径前缀，为空表示不进行过滤  
	        repository.log(new String[]{""},  
	                       startRevision,  
	                       endRevision,  
	                       true,  
	                       true,  
	                       new ISVNLogEntryHandler() {  
	                           @Override  
	                           public void handleLogEntry(SVNLogEntry svnlogentry)  
	                                   throws SVNException {  
	                //依据提交时间进行过滤  
	                               if (svnlogentry.getDate().after(begin)  
	                                   && svnlogentry.getDate().before(end)) {  
	                                   // 依据提交人过滤  
	                                   if (!"".equals(author)) {  
	                                       if (author.equals(svnlogentry.getAuthor())) {  
	                                           fillResult(svnlogentry);  
	                                       }  
	                                   } else {  
	                                       fillResult(svnlogentry);  
	                                   }  
	                               }  
	                           }  
	  
	                           public void fillResult(SVNLogEntry svnlogentry) {  
	                          //getChangedPaths为提交的历史记录MAP key为文件名，value为文件详情  
	                               //history.addAll(svnlogentry.getChangedPaths().keySet()); 
	                        	   List<String> total = new ArrayList<String>();
	                        	   
	                        	   String key = svnlogentry.getAuthor();
	                        	   if (!totalByAnthor.containsKey(key)) {
	                        		   totalByAnthor.put(key, new ArrayList<>());
	                        	   }
	                        	   
	                        	   for (SVNLogEntryPath ep : svnlogentry.getChangedPaths().values()) {
	                        		   if (SVNNodeKind.FILE == ep.getKind() && 'D' != ep.getType() ) {
	                        			   if (!totalByAnthor.get(key).contains(ep.getPath()))
	                        				   totalByAnthor.get(key).add(ep.getPath());
	                        		   }
	                        	   }
	                        	   
	                           }  
	                       });  
	        
	        List<VcsDayStat> list = new ArrayList<>();
	        for (String key : totalByAnthor.keySet()) {  
	        	VcsDayStat stats = new VcsDayStat();
	        	stats.setUser(key);
	        	stats.setStatDate(begin);
	        	stats.setFileTotal(totalByAnthor.get(key).size());
	        	list.add(stats);
	        }  
	        
	        return list;
        } catch (SVNException svne) {
        	svne.printStackTrace();
        }
        
        return null;
	}
	
	public List<VcsMonthStat> getLastMonthStatList() {
		
		DAVRepositoryFactory.setup();
		
        //定义svn版本库的URL。
        SVNURL repositoryURL = null;
        //定义版本库。
        SVNRepository repository = null;
        /*
         * 实例化版本库类
         * */
        try {
        	//获取SVN的URL。
        	repositoryURL=SVNURL.parseURIEncoded(repoUrl);
        	//根据URL实例化SVN版本库。

        	ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        	 
    		// 实例化客户端管理类
        	SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, username, password);

        	repository = clientManager.createRepository(repositoryURL, false);

        } catch (SVNException svne) {
            svne.printStackTrace();
        }
    	
        try {
	        // 过滤条件  
        	Calendar cal1 = Calendar.getInstance();
        	cal1.add(Calendar.DAY_OF_MONTH, 1);
        	cal1.set(Calendar.HOUR_OF_DAY, 0);
        	cal1.set(Calendar.MINUTE, 0);
        	cal1.set(Calendar.SECOND, 0);
        	cal1.set(Calendar.MILLISECOND, 0);
        	final Date end = cal1.getTime();

        	cal1.set(Calendar.DAY_OF_MONTH, 1);
        	final Date begin = cal1.getTime();
        	
	        final String author = "";  
	        long startRevision = 0;  
	        long endRevision = -1;//表示最后一个版本  
	        final Map<String, List<String>> totalByAnthor = new HashMap<>();  
	        
	        //String[] 为过滤的文件路径前缀，为空表示不进行过滤  
	        repository.log(new String[]{""},  
	                       startRevision,  
	                       endRevision,  
	                       true,  
	                       true,  
	                       new ISVNLogEntryHandler() {  
	                           @Override  
	                           public void handleLogEntry(SVNLogEntry svnlogentry)  
	                                   throws SVNException {  
	                //依据提交时间进行过滤  
	                               if (svnlogentry.getDate().after(begin)  
	                                   && svnlogentry.getDate().before(end)) {  
	                                   // 依据提交人过滤  
	                                   if (!"".equals(author)) {  
	                                       if (author.equals(svnlogentry.getAuthor())) {  
	                                           fillResult(svnlogentry);  
	                                       }  
	                                   } else {  
	                                       fillResult(svnlogentry);  
	                                   }  
	                               }  
	                           }  
	  
	                           public void fillResult(SVNLogEntry svnlogentry) {  
	                          //getChangedPaths为提交的历史记录MAP key为文件名，value为文件详情  
	                               //history.addAll(svnlogentry.getChangedPaths().keySet()); 
	                        	   List<String> total = new ArrayList<String>();
	                        	   
	                        	   String key = svnlogentry.getAuthor();
	                        	   if (!totalByAnthor.containsKey(key)) {
	                        		   totalByAnthor.put(key, new ArrayList<>());
	                        	   }
	                        	   
	                        	   for (SVNLogEntryPath ep : svnlogentry.getChangedPaths().values()) {
	                        		   if (SVNNodeKind.FILE == ep.getKind() && 'D' != ep.getType() ) {
	                        			   if (!totalByAnthor.get(key).contains(ep.getPath()))
	                        				   totalByAnthor.get(key).add(ep.getPath());
	                        		   }
	                        	   }
	                        	   
	                           }  
	                       });  
	        
	        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM");
	        
	        List<VcsMonthStat> list = new ArrayList<>();
	        for (String key : totalByAnthor.keySet()) {  
	        	VcsMonthStat stats = new VcsMonthStat();
	        	stats.setUser(key);
	        	stats.setStatMonth(fmt.format(begin));
	        	stats.setFileTotal(totalByAnthor.get(key).size());
	        	list.add(stats);
	        }  
	        
	        return list;
        } catch (SVNException svne) {
        	svne.printStackTrace();
        }
        
        return null;
        
	}
}
